package com.a3dweijing.wetouch2.Activity;

import android.Manifest;
import android.app.DownloadManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.a3dweijing.wetouch2.R;
import com.a3dweijing.wetouch2.Util.SharedPreUtil;
import com.a3dweijing.wetouch2.Util.VersionUtil;
import com.a3dweijing.wetouch2.base.BaseActivity;
import com.a3dweijing.wetouch2.bean.VersionMsg;
import com.a3dweijing.wetouch2.fragment.FragmentOf3D;
import com.a3dweijing.wetouch2.fragment.HomePageFragment;
import com.a3dweijing.wetouch2.fragment.ShoppingCartFragment;
import com.a3dweijing.wetouch2.fragment.UserFragment;
import com.a3dweijing.wetouch2.fragment.VideoPlayFragment;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.iwf.photopicker.PhotoPicker;
import okhttp3.Call;

import static com.a3dweijing.wetouch2.Util.PermissionapplicationHelp.QUANXIANCODE;

public class MainActivity extends BaseActivity
{
    
    @BindView(R.id.realtabcontent)
    FrameLayout realtabcontent;
    
    @BindView(android.R.id.tabcontent)
    FrameLayout tabcontent;
    
    @BindView(android.R.id.tabhost)
    FragmentTabHost mTabHost;
    
    @BindView(R.id.frame)
    FrameLayout frame;
    
    private LayoutInflater mInflater;
    
    private boolean isfrist = true;
    
    private String url;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initView();
        isUpdate();
    }
    
    public void initView()
    {
        mInflater = LayoutInflater.from(this);
        mTabHost = (FragmentTabHost)this.findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        String[] tags = new String[] {"home", "shopping", "3d", "user"};
        String[] names = new String[] {"首页", "商城", "2d/3d", "我的"};
        Drawable[] img = new Drawable[] {getResources().getDrawable(R.drawable.main_home_selector),
            getResources().getDrawable(R.drawable.main_shopping_selector),
            getResources().getDrawable(R.drawable.main_3d_selector),
            getResources().getDrawable(R.drawable.main_user_selector)};
        Class[] classes =
            new Class[] {HomePageFragment.class, ShoppingCartFragment.class, FragmentOf3D.class, UserFragment.class};
        
        for (int i = 0; i < tags.length; i++)
        {
            TabHost.TabSpec tabSpec1 = mTabHost.newTabSpec(tags[i]);
            View view = creatView(R.layout.tab_item, names[i]);
            ImageView viewById = view.findViewById(R.id.image_icon);
            viewById.setImageDrawable(img[i]);
            tabSpec1.setIndicator(view);
            mTabHost.addTab(tabSpec1, classes[i], null);
        }
        
    }
    
    public View creatView(@NonNull int resource, String name)
    {
        
        View view = mInflater.inflate(resource, null);
        ImageView img = (ImageView)view.findViewById(R.id.image_icon);
        TextView text = (TextView)view.findViewById(R.id.text_content);
        text.setText(name);
        return view;
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE)
        {
            if (data != null)
            {
                Fragment fragment = getSupportFragmentManager().findFragmentByTag("user");
                fragment.onActivityResult(PhotoPicker.REQUEST_CODE, RESULT_OK, data);
            }
        }
    }
    
    // @Override
    // public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    // super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    // if (requestCode == QUANXIANCODE && permissions.length > 0 &&
    // permissions[0].equals(Manifest.permission.ACCESS_COARSE_LOCATION)) {
    // Fragment fragment = getSupportFragmentManager().findFragmentByTag("shopping");
    // fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
    // }
    // }
    public void setFrameHide()
    {
        frame.removeAllViews();
        frame.setVisibility(View.GONE);
    }
    
    public void setFrameShow(String url)
    {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.frame, VideoPlayFragment.getInctance(url), "tag1").commit();
        frame.setVisibility(View.VISIBLE);
    }
    
    public void isUpdate()
    {
        if (isfrist)
        {
            OkGo.post("http://wetouch.3dweijing.com/angaHtm/findVersions").tag(getBaseContext()).execute(
                new StringCallback()
                {
                    @Override
                    public void onSuccess(String s, Call call, okhttp3.Response response)
                    {
                        Log.e("--", "onSuccess: " + s);
                        VersionMsg m = new Gson().fromJson(s, VersionMsg.class);
                        if (m.isFlag())
                        {
                            int versions_update_explain = Integer.parseInt(m.getList().get(0).getVersions_update_explain());
                            if (versions_update_explain > VersionUtil.getLocalVersion(getApplication()))
                            {
                                showresetpopupwindow(m.getList().get(0));
                            }
                        }
                    }
                });
            isfrist = false;
            
        }
    }
    
    public void showresetpopupwindow(final VersionMsg.ListBean bean)
    {
        View v = LayoutInflater.from(MainActivity.this).inflate(R.layout.popwindow_appset_check_new_version, null);
        final PopupWindow window =
            new PopupWindow(v, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        TextView submit = (TextView)v.findViewById(R.id.popwindow_appset_check_new_version_submit);
        TextView cancel = (TextView)v.findViewById(R.id.popwindow_appset_check_new_version_cancel);
        TextView version = (TextView)v.findViewById(R.id.popwindow_appset_check_new_version_name);
        TextView size = (TextView)v.findViewById(R.id.popwindow_appset_check_new_version_size);
        TextView detail = (TextView)v.findViewById(R.id.popwindow_appset_check_new_version_detail);
        window.setBackgroundDrawable(new ColorDrawable(0x00000000));
        version.setText("最新版本号：" + bean.getVersions_name());
        size.setText("新版本大小：");
        detail.setText("更新说明：" + bean.getVersions_update_explain());
        submit.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                url = bean.getVersions_download_url();
                window.dismiss();
                if (ContextCompat.checkSelfPermission(getBaseContext(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
                {
                    downloudfile();
                }
                else
                {
                    ActivityCompat.requestPermissions(MainActivity.this,
                        new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        21);
                }
            }
        });
        cancel.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                window.dismiss();
                
            }
        });
        window.setBackgroundDrawable(new ColorDrawable(0x00000));
        window.setTouchInterceptor(new View.OnTouchListener()
        {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent)
            {
                return false;
            }
        });
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        window.setFocusable(true);
        window.setOnDismissListener(new PopupWindow.OnDismissListener()
        {
            @Override
            public void onDismiss()
            {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        window.showAtLocation(v, Gravity.CENTER, 0, 0);
        
    }
    
    public void downloudfile()
    {
        DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL | DownloadManager.STATUS_RUNNING
            | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING);
        Cursor cursor = downloadManager.query(query);
        ArrayList<Long> ids = new ArrayList<Long>();
        while (cursor != null && cursor.moveToNext())
        {
            if (cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME)).endsWith(".apk"))
            {
                ids.add(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
            }
        }
        for (Long item : ids)
        {
            downloadManager.remove(item);
        }
        File file =
            new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "update.apk");
        if (file.exists())
        {
            file.deleteOnExit();
        }
        DownloadManager.Request request = null;
        
        request = new DownloadManager.Request(Uri.parse(url));
        
        request.setDestinationUri(Uri.fromFile(file));
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setTitle("下载更新...");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setVisibleInDownloadsUi(true);
        request.setAllowedOverRoaming(true);
        request.allowScanningByMediaScanner();
        try
        {
            long downloadId = downloadManager.enqueue(request);
            SharedPreUtil.put(getBaseContext(), "plato", downloadId);
        }
        catch (IllegalArgumentException e)
        {
            Toast.makeText(MainActivity.this, "检测到您的系统中下载组件被移除，请重置手机以恢复该组件。", Toast.LENGTH_LONG).show();
        }
    }
}
